<template>
  <div class="my-cover">
    <!-- 图片按钮 -->
    <div class="btn_img" @click="openDialog">
      <img :src=" value || imgSrc" />
    </div>
    <!-- 对话框 -->
    <el-dialog
      title="选择封面"
      :append-to-body="true"
      :visible.sync="dialogVisible"
      width="720px"
    >
      <!-- tab组件 -->
      <el-tabs v-model="activeName" type="card">
        <el-tab-pane label="素材库" name="image">
          <div class="top-box">
            <el-radio-group
              size="medium"
              v-model="collect"
              @change="changeCollect"
            >
              <el-radio-button :label="false">全部</el-radio-button>
              <el-radio-button :label="true">收藏</el-radio-button>
            </el-radio-group>
          </div>
          <el-row :gutter="10" class="img_list">
            <el-col
              @click.native="selectedImg(item)"
              class="img_item"
              :class="{ selected: item.url === selectedUrl }"
              v-for="item in images"
              :key="item.id"
              :xs="12"
              :sm="8"
              :md="6"
              :lg="4"
              :xl="4"
            >
              <el-image
                style="height: 100px; width: 100%"
                :src="item.url"
                fit="cover"
              >
              </el-image>
            </el-col>
          </el-row>
          <el-pagination
            background
            @current-change="changePage"
            layout="prev, pager, next"
            :current-page="page"
            :page-size="per_page"
            :total="total_count"
          >
          </el-pagination>
        </el-tab-pane>
        <el-tab-pane label="上传图片" name="upload">
          <el-upload
            class="avatar-uploader"
            :action= "$http.defaults.baseURL + '/mp/v1_0/user/images'"
            :headers= 'headers'
            name="image"
            :show-file-list="false"
            :on-success="handleSuccess"
            :before-upload="beforeUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-tab-pane>
      </el-tabs>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleConfirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { reqGetImages } from '@/api/pictures.js'
import { getUser } from '@/utils/storage.js'
import DefaultImg from '@/assets/default.png'
export default {
  name: 'MyCover',
  data () {
    return {
      // 控制对话框显示隐藏
      dialogVisible: false,
      // 当前tabs组件激活的选项卡的name属性的值
      activeName: 'image',
      images: [],
      page: 1,
      per_page: 4,
      total_count: 0,
      collect: false,
      selectedUrl: '', // 选中图片的地址
      imageUrl: '', // 上传的图片地址
      imgSrc: DefaultImg, // 预览图片
      headers: {
        Authorization: `Bearer ${getUser().token}`
      }
    }
  },
  props: ['value'],
  created () {
    this.getImages()
  },
  methods: {
    openDialog () {
      this.dialogVisible = true
    },
    async getImages () {
      try {
        const res = await reqGetImages({
          collect: this.collect,
          page: this.page,
          per_page: this.per_page
        })
        this.images = res.data.data.results
        this.total_count = res.data.data.total_count
        // console.log(res.data)
      } catch (err) {
        console.log(err)
      }
    },
    changePage (index) {
      this.page = index
      this.getImages()
    },
    changeCollect () {
      this.page = 1
      this.getImages()
    },
    // 点了图片就把类添加上 根据图片地址确定是否选中
    selectedImg (item) {
      // console.log(item)
      this.selectedUrl = item.url
    },
    handleSuccess (res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    handleConfirm () {
      if (this.activeName === 'image') {
        if (this.selectedUrl === '') {
          this.$message.error('请选择图片')
          return
        }
        this.imgSrc = this.selectedUrl
        console.log(this.selectedUrl)
      }
      if (this.activeName === 'upload') {
        if (this.imageUrl === '') {
          this.$message.error('请上传图片')
          return
        }
        this.imgSrc = this.imageUrl
      }
      this.$emit('input', this.imgSrc)
      this.dialogVisible = false
    }
  }
}
</script>

<style scoped lang='less'>
// 图片按钮
// 图片按钮
.btn_img {
  width: 150px;
  height: 150px;
  border: 1px dashed #ddd;
  img {
    width: 100%;
    height: 100%;
    display: block;
  }
}
// 素材列表
.img_list {
  margin-top: 15px;
  .img_item {
    width: 150px;
    height: 120px;
    border: 1px dashed #ddd;
    display: inline-block;
    margin-right: 15px;
    position: relative;
    img {
      width: 100%;
      height: 100%;
      display: block;
    }
  }
}
// <div class="selected"></div>
.selected::after {
  content: "";
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.3) url(../assets/selected.png) no-repeat center /
    50px 50px;
}
.avatar-uploader {
  text-align: center;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar-uploader /deep/ .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
</style>
